package com.framework.util.generator;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @包名 :com.guitar.pub.generator
 * @文件名 :FreeMarkers.java
 *      TODO 类作用：freemarker工具类
 * @Author: luobaolin 543414648@qq.com
 * @Date: 2014-7-24 下午1:28:05
 */
public class FreeMarkers {

	private static Configuration configuration = new Configuration();

	static {
		configuration.setDefaultEncoding("UTF-8");
		configuration.setDateFormat("yyyy-MM-dd HH:mm:ss");
		configuration.setNumberFormat("#0.#");
	}

	public static String renderString(String templateString, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template t = new Template("name", new StringReader(templateString), configuration);
			t.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String renderTemplate(Template template, Object model) {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Configuration buildConfiguration(String directory) throws IOException {
		Configuration cfg = new Configuration();
		Resource path = new DefaultResourceLoader().getResource(directory);
		cfg.setDirectoryForTemplateLoading(path.getFile());
		return cfg;
	}

	public static void main(String[] args) throws IOException {
		// renderString
		Map<String, String> model = new HashMap<String, String>();
		model.put("userName", "xiaoluo");
		String result = FreeMarkers.renderString("hello ${userName}\ndsd", model);
		System.out.println(result);
		// // renderTemplate
		// Configuration cfg = FreeMarkers.buildConfiguration("classpath:templates/");
		// Template template = cfg.getTemplate("java_entity.ftl");
		// String result2 = FreeMarkers.renderTemplate(template, model);
		// System.out.println(result2);
	}

}